/**
 * Author: w景洋.
 * Time: 2016/4/29 0029
 */
angular.module('service.payment', [
        'ngResource',
        'ngStorage',
    ])

    //微信支付的接口
    .service('WxpayService', ['$resource', '$localStorage', function ($resource, $localStorage) {
        var openid_res = $resource(mall_payconfig.wxpay_reaurl + "openid");
        var jsapipay_res = $resource(mallorder + "orderspay/wxjsapipay/" + mall_payconfig.wxpay_spid + "/:openid");
        var apppay_res = $resource(mallorder + "orderspay/wxapppay/" + mall_payconfig.wxapppay_spid);
        var WxpayService = this;
        var $storage = $localStorage.$default({
            name: '',
            userId: '',
            wxpay_openid: '',
            order: '',
        });
        this.jspiPay = function (payInfo, success_func, error_func) {
            if (!$storage.wxpay_openid) {
                var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                var authcode = "xxxxxxxxxxxxxxxxxx";
                if (r) {
                    authcode = unescape(r[2]);
                }
                openid_res.get({wxspid: mall_payconfig.wxpay_spid, code: authcode}).$promise.then(function (data) {

                    if (data.openid) {
                        $storage.wxpay_openid = data.openid;
                        payInfo.openid = data.openid;
                        WxpayService.wxpayjsapipay(payInfo, success_func, error_func);
                    } else {
                        var jump_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
                            + mall_payconfig.wxpay_appid + "&redirect_uri=" + mall_payconfig.wxpay_backurl
                            + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
                        window.location.href = jump_url;
                    }
                }, function (error) {
                    //alert(error);
                });
            }
            else {
                payInfo.openid = $storage.wxpay_openid;
                //支付调起
                return WxpayService.wxpayjsapipay(payInfo, success_func, error_func);
            }
        }

        this.wxpayjsapipay = function (payInfo, success_func, error_func) {

            //支付调起
            return jsapipay_res.save({openid: payInfo.openid}, payInfo, success_func, error_func);
        }

        this.appPay = function (payInfo, success_func, error_func) {

            //支付调起
            return apppay_res.save({}, payInfo, success_func, error_func);
        }
    }])

    //支付宝手机网页支付
    .service('AliWapPay', ['$resource', '$http', '$q', '$window', 'OrderService', function ($resource, $http, $q, $window, OrderService) {
        //预支付
        this.webPay = function (data) {
            data.show_url = mall_payconfig.alipay_callback;
            data.return_url = mall_payconfig.alipay_callback;
            var deferred = $q.defer();
            $http({
                method: "POST",
                url: mall_payconfig.alipay_url + mall_payconfig.alipay_appid,
                data: data
            }).success(function (data, status, headers, config) {
                deferred.resolve(data);
            }).error(function (data, status, headers, config) {
                deferred.reject(data);
            });
            return deferred.promise;
        };
        this.aliAppPay = function (order_info, success, error) {
            var apppay_url = $resource(mall_payconfig.aliapppay_url + ":sellerid");
            return apppay_url.save({sellerid: mall_payconfig.alipay_appid}, order_info, success, error)
        }
        this.AppPay = function (reason, order_info) {
            var myDate = new Date();
//            var order_info = order_info;
//            var tradeNo = order_info.orderid;
            var Ali_payClass = navigator.alipay;
            var rsa = "";
            var pubRsa = "";
            if (Ali_payClass != null)
                Ali_payClass.pay({
                    "partner": mall_payconfig.alipay_appid,    //商户ID
                    //如果要在ALIPAY。JAVA文件里加入钥匙，在这里的钥匙应该删掉，仅仅注释不能保证安全
                    "seller": mall_payconfig.alipay_appid,    //收款支付宝账号或对应的支付宝唯一用户号
                    "subject": "农归吧订单",             //商品名称
                    "body": "支付宝支付",        //商品详情
                    "price": "" + reason.totalFee,                  //金额
                    "tradeNo": "" + reason.payid,
                    "timeout": "30m",                 //超时设置
                    "notifyUrl": mall_payconfig.aliapppay_callback
                }, function (resultStatus) {
                    if (resultStatus == 6001) {
                        input_alert("支付宝支付取消");
                    }
                    else if (resultStatus == 9000) {
                        input_alert("支付成功", 1000);
                        OrderService.delcacheid();
                        setTimeout(function () {
                            $window.location.href = projectBaseUrl + "orderlist/2";
                        }, 1000);
                    }
                    else if (resultStatus == 4000) {
                        input_alert("你尚未安装支付宝客户端,即将通过支付在线页支付");
                        this.webPay(order_info).then(function (data) {
                            $window.location.href = data;
                        })
                        $window.location.href = projectBaseUrl + "myview";
                    }
                    else {
                        input_alert("支付宝支付失败");
                    }
                }, function (message) {
                    input_alert(
                        "支付宝支付发送失败"
                    );
                });
            else {
                input_alert("未找到支付宝app，跳转到网页支付");
                this.webPay(order_info).then(function (data) {
                    $window.location.href = projectBaseUrl + "myview";
                    $window.location.href = data;
                });
            }
        }
    }])

    //余额支付的接口
    .service('YuepayService', ['$resource', 'MallAuthService', function ($resource, MallAuthService) {
        this.yuepay = function (data, success, error) {
            //支付调起
            var id = MallAuthService.getUserid();
            var userbalpay = $resource(mallorder + 'orderspay/balancepay/:userid');
            return userbalpay.save({userid: id}, data, success, error);
        }
    }])
    .service('PayService', ['$resource','$localStorage', function ($resource,$localStorage) {
        var $storage = $localStorage.$default({
            wxpay_openid: '',
        });
        this.createPay = function(payCreate){
            var resource = $resource(mallpay_url + "orderspay/create/:orderid");
            return resource.save({orderid: orderid,paystyle:paystyle}, orderspay, success, error);
        };
        this.testPay = function (orderid, paystyle, orderspay,success, error) {
            var resource = $resource(mallpay_url + "orderspay/unifypay/:orderid");
            return resource.save({orderid: orderid,paystyle:paystyle}, orderspay, success, error);
        };
        //通过订单id获取商户支付配置
        this.getPaystyle = function(orderid){
            console.log(orderid);
            var resource = $resource(mallpay_url + "shopspayconfig/byorderid/:orderid");
            return resource.query({orderid:orderid});
        };
    }])
    .service('PayConfig', [function () {
        var pay_config = undefined;
        this.setPayConfig = function (config) {
            pay_config = config;
        };
        this.getPayConfig = function() {
            return pay_config;
        }
    }])
;